﻿using CastingWellEquipmentGUI.Config;
using CastingWellEquipmentGUI.Model;
using CastingWellEquipmentGUI.View.UserControls;
using CastingWellEquipmentGUI.ViewModel.Common.LogTool;
using Confluent.Kafka;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CastingWellEquipmentGUI.Utils
{
    public static class KafkaHelper
    {
        private static string bootstrapServers = "192.168.62.174:9092";
        //private static string bootstrapServers = SystemConfig.dataBaseIpAddress + ":9092";
        private static string group1 = "group.1";
        private static ProducerBuilder<string, object> producerBuilder;
        private static IProducer<string, object> producer;
        private static int partition = 0;
        private static TopicPartition topicPartition = null;
        private static TopicPartition topicHeartBeatPartition = null;

        public static bool InItProduce()
        {
            try
            {
                producerBuilder = new ProducerBuilder<string, object>(new ProducerConfig
                {
                    BootstrapServers = bootstrapServers
                });
                producerBuilder.SetValueSerializer(new KafkaConverter());//设置序列化方式
                producer = producerBuilder.Build();
                topicPartition = new TopicPartition("BusinessCmd", new Partition(partition));
                topicHeartBeatPartition = new TopicPartition("Heartbeat", new Partition(partition));
                return true;
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "初始化Kafka生产者");
            }
            return false;

        }
        public static bool ProduceMessage(string Message)
        {
            try
            {
                producer.Produce(topicPartition, new Message<string, object>() { Key = "TagValueChange", Value = Message });
                return true;
            }
            catch (Exception ex)
            {
                LogTool.SaveSysLog(ex.Message, "Kafka生产者发送消息");
                producer.Dispose();
                if (InItProduce())
                {
                    producer.Produce(topicPartition, new Message<string, object>() { Key = "TagValueChange", Value = Message });
                    return true;
                }
            }
            return false;
        }

        private static ConsumerBuilder<string, object> consumerBuilder = null;
        private static IConsumer<string, object> consumer = null;
        private static ConsumerBuilder<string, object> consumerChangeValueBuilder = null;
        private static IConsumer<string, object> consumerChangeValue = null;
        public static bool InitConsumerByTagValueChanged()
        {
            try
            {
                ConsumerConfig config = new ConsumerConfig();
                config.BootstrapServers = bootstrapServers;
                config.GroupId = group1;
                config.AutoOffsetReset = AutoOffsetReset.Earliest;
                config.EnableAutoCommit = false;
                consumerBuilder = new ConsumerBuilder<string, object>(config);
                consumerBuilder.SetValueDeserializer(new KafkaConverter());//设置反序列化方式
                consumer = consumerBuilder.Build();
                consumer.Assign(new TopicPartition("TagValueChanged", new Partition(0)));//从指定的Partition订阅消息使用Assign方法
                return true;
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "初始化Kafka消费者");
            }
            return false;
        }

        public static bool InitConsumerByTagChangeValue()
        {
            try
            {
                ConsumerConfig config = new ConsumerConfig();
                config.BootstrapServers = bootstrapServers;
                config.GroupId = group1;
                config.AutoOffsetReset = AutoOffsetReset.Earliest;
                config.EnableAutoCommit = false;
                consumerChangeValueBuilder = new ConsumerBuilder<string, object>(config);
                consumerChangeValueBuilder.SetValueDeserializer(new KafkaConverter());//设置反序列化方式
                consumerChangeValue = consumerChangeValueBuilder.Build();
                consumerChangeValue.Assign(new TopicPartition("BusinessCmdResult", new Partition(0)));//从指定的Partition订阅消息使用Assign方法
                return true;
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "初始化Kafka消费者");
            }
            return false;
        }

        public static IConsumer<string, object> GetConsumer()
        {
            if (consumer == null)
            {
                consumer.Dispose();
                InitConsumerByTagValueChanged();
            }
            return consumer;
        }
        public static IConsumer<string, object> GetConsumerChangeValue()
        {
            if (consumerChangeValue == null)
            {
                consumerChangeValue.Dispose();
                InitConsumerByTagChangeValue();
            }
            return consumerChangeValue;
        }

        public static HashSet<Control> UpdateCurrentUserTagValue(int Id, string value, string ShowPageTitle)
        {
            HashSet<Control> result = new HashSet<Control>();
            for (int i = 0; i < LogTool.CurrentUser.Roles.Count; i++)
            {
                for (int j = 0; j < LogTool.CurrentUser.Roles[i].Permissions.Count; j++)
                {
                    if (LogTool.CurrentUser.Roles[i].Permissions[j].PForm != null &&
                        LogTool.CurrentUser.Roles[i].Permissions[j].PForm.FormName == ShowPageTitle &&
                        LogTool.CurrentUser.Roles[i].Permissions[j].PControl != null &&
                        LogTool.CurrentUser.Roles[i].Permissions[j].PControl.Tag.Id == Id)
                    {
                        result.Add(new Control
                        {
                            ControlId = LogTool.CurrentUser.Roles[i].Permissions[j].PControl.ControlId,
                            ControlName = LogTool.CurrentUser.Roles[i].Permissions[j].PControl.ControlName
                        });
                        LogTool.CurrentUser.Roles[i].Permissions[j].PControl.Tag.Value = value;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 根据Key获取Redis中监控标签的值
        /// </summary>
        /// <param name="key">Redis监控标签表的键</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public static string GetTagValueByKey(string key)
        {
            TagInfo tag = RedisHelper.GetHashKey<TagInfo>("Tag_Value", key);
            if (SystemConfig.SystemStatus != "网络中断")
            {
                if (tag != null)
                {
                    return RedisHelper.GetHashKey<TagInfo>("Tag_Value", key).Value;
                }
            }
            return null;
        }

        public static ObservableCollection<AlarmModel> GetAlarms()
        {
            ObservableCollection<AlarmModel> resultObservableCollection = new ObservableCollection<AlarmModel>();
            ObservableCollection<RedisAlarming> results = RedisHelper.GetHashAllToOc<RedisAlarming>("Alarming");
            for (int i = 0; i < results.Count; i++)
            {
                RedisAlarming alarming = results[i];
                AlarmModel alarmModel = new AlarmModel
                {
                    OrderNo = i + 1
                };
                if (alarming != null)
                {
                    switch (alarming.Severity)
                    {
                        case 1:
                            alarmModel.AlarmLevel = "一级报警";
                            break;
                        case 2:
                            alarmModel.AlarmLevel = "二级报警";
                            break;
                        case 3:
                            alarmModel.AlarmLevel = "三级报警";
                            break;
                    }
                    alarmModel.AlarmContent = alarming.AlarmText;
                    alarmModel.AlarmDateTime = alarming.EventTime;
                    resultObservableCollection.Add(alarmModel);
                }
            }
            return resultObservableCollection;
        }

        /// <summary>
        /// 根据Key获取Redis中监控标签的Double值
        /// </summary>
        /// <param name="key">Redis监控标签表的键</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public static double GetTagDoubleValueByKey(string key)
        {
            if (SystemConfig.SystemStatus != "网络中断")
            {
                return double.Parse(RedisHelper.GetHashKey<TagInfo>("Tag_Value", key).Value);
            }
            return 0;
        }


        private static ConsumerBuilder<string, object> alarmConsumerBuilder = null;
        private static IConsumer<string, object> alarmConsumer = null;
        public static bool InitConsumerByAlarm()
        {
            try
            {
                ConsumerConfig config = new ConsumerConfig
                {
                    BootstrapServers = bootstrapServers,
                    GroupId = group1,
                    AutoOffsetReset = AutoOffsetReset.Earliest,
                    EnableAutoCommit = false
                };
                alarmConsumerBuilder = new ConsumerBuilder<string, object>(config);
                alarmConsumerBuilder.SetValueDeserializer(new KafkaConverter());//设置反序列化方式
                alarmConsumer = alarmConsumerBuilder.Build();
                alarmConsumer.Assign(new TopicPartition("Alarming", new Partition(0)));//从指定的Partition订阅消息使用Assign方法
                return true;
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "初始化Kafka消费者");
            }
            return false;
        }

        public static IConsumer<string, object> GetAlarmConsumer()
        {
            if (alarmConsumer == null)
            {
                alarmConsumer.Dispose();
                InitConsumerByAlarm();
            }
            return alarmConsumer;
        }

        /// <summary>
        /// 给网关发送消息
        /// 方法1
        /// </summary>
        /// <param name="showPageTitle">页面名称</param>
        /// <param name="ControlName">控件名称</param>
        /// <param name="Value">修改值</param>
        /// <returns></returns>
        public static bool SendGatewayChangeTagMessage(string showPageTitle, string ControlName, string Value)
        {
            // 创建发送给网关实例对象
            BusinessCmd businessCmd = new BusinessCmd
            {
                Guid = Guid.NewGuid().ToString(),
                BusinessCmdCode = 3,
                TagId = TagTool.GetTagIdByValueByFormNameAndControlName(showPageTitle, ControlName),
                TagValue = Value
            };

            return SendGatewayBusinessCmd(businessCmd);
        }

        /// <summary>
        /// 给网关发送消息
        /// 方法2
        /// </summary>
        /// <param name="TagValue">修改对象</param>
        /// <returns></returns>
        public static bool SendGatewayBusinessCmd(BusinessCmd businessCmd)
        {
            // 判断心跳状态
            if (SystemConfig.SystemStatus == "网络中断")
            {
                return false;
            }

            /** 1、先消耗掉心跳结果队列中的消息 **/
            while (true)
            {
                var resultother = consumerChangeValue.Consume(100);
                if (resultother != null)
                {
                    consumerChangeValue.Commit(resultother);
                }
                else
                {
                    break;
                }
            }

            /** 2、发送报警记录归档指令给网关服务器 **/
            // Kafka消费者断线重连
            GetConsumerChangeValue();
            // 将实例序列化
            string jsonStr = JsonConvert.SerializeObject(businessCmd);
            // 发送消息到Kafka
            if (KafkaHelper.ProduceMessage(jsonStr))
            {
                /** 3、接收命令执行反馈 **/
                // Kafka阻塞消费(最长阻塞时间1000ms)
                var result = consumerChangeValue.Consume(1000);
                if (result != null)
                {
                    consumerChangeValue.Commit(result);
                    BusinessCmdResult businessCmdResult = JsonConvert.DeserializeObject<BusinessCmdResult>(result.Message.Value.ToString());
                    if (businessCmd.Guid == businessCmdResult.Guid && businessCmdResult.result == true)
                    {
                        // 发送成功
                        return true;
                    }
                    else if (businessCmd.Guid == businessCmdResult.Guid && businessCmdResult.result == false)
                    {
                        // 发送失败
                        return false;
                    }
                    else
                    {
                        // 发送失败
                        return false;
                    }
                }
                else
                {
                    // 发送失败
                    return false;
                }
            }
            else
            {
                // 发送失败
                return false;
            }
        }


        #region 心跳通讯
        /// <summary>
        /// 给网关发送消息（心跳检测）
        /// </summary>
        /// <param name="TagValue">修改对象</param>
        /// <returns></returns>
        public static bool SendHeartBeat(HeartBeatInfoModel heartBeat)
        {
            // Kafka消费者断线重连
            GetConsumerHeartBeat();
            // 改值结果 true=修改成功，false=修改失败
            bool SendResult = false;
            // 将实例序列化
            string jsonStr = JsonConvert.SerializeObject(heartBeat);
            // 发送消息到Kafka
            if (KafkaHelper.ProduceHeartBeatMessage(jsonStr))
            {
                SendResult = true;
            }
            return SendResult;
        }

        public static IConsumer<string, object> consumerHeartBeat = null;
        /// <summary>
        /// 心跳监听对象实例化
        /// </summary>
        /// <returns></returns>
        public static IConsumer<string, object> GetConsumerHeartBeat()
        {
            if (consumerHeartBeat == null)
            {
                InitConsumerByHeartBeat();
            }
            return consumerHeartBeat;
        }
        private static ConsumerBuilder<string, object> consumerHeartBeatBuilder = null;
        /// <summary>
        /// 心跳监听对象实例化
        /// </summary>
        /// <returns></returns>
        public static bool InitConsumerByHeartBeat()
        {
            try
            {
                ConsumerConfig config = new ConsumerConfig();
                config.BootstrapServers = bootstrapServers;
                config.GroupId = group1;
                config.AutoOffsetReset = AutoOffsetReset.Earliest;
                config.EnableAutoCommit = false;
                consumerHeartBeatBuilder = new ConsumerBuilder<string, object>(config);
                consumerHeartBeatBuilder.SetValueDeserializer(new KafkaConverter());//设置反序列化方式
                consumerHeartBeat = consumerHeartBeatBuilder.Build();
                consumerHeartBeat.Assign(new TopicPartition("HeartbeatResult", new Partition(0)));//从指定的Partition订阅消息使用Assign方法
                return true;
            }
            catch (Exception e)
            {
                LogTool.SaveSysLog(e.Message, "初始化Kafka消费者");
            }
            return false;
        }

        /// <summary>
        /// 心跳消息发送
        /// </summary>
        /// <param name="Message"></param>
        /// <returns></returns>
        public static bool ProduceHeartBeatMessage(string Message)
        {
            try
            {
                producer.Produce(topicHeartBeatPartition, new Message<string, object>() { Key = "Heartbeat", Value = Message });
                return true;
            }
            catch (Exception ex)
            {
                LogTool.SaveSysLog(ex.Message, "Kafka生产者发送消息");
                producer.Dispose();
                if (InItProduce())
                {
                    producer.Produce(topicHeartBeatPartition, new Message<string, object>() { Key = "Heartbeat", Value = Message });
                    return true;
                }
            }
            return false;
        }

        #endregion 心跳通讯

    }
}
